<template>
  <div id="MenList">
    <Splitpanes>
      <Pane>
        <div class="menuTable">
          <!-- <div>
            <button @click="toggleTheme">切换主题</button>
            <div :class="themeClass" class="demo-element">示例元素</div>
          </div> -->
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">菜单</div>
              <vxe-input clearable class="vxeInputSearch" placeholder="关键字查询" type="search" v-model="keywords" @search-click="search" @keyup="keyup"></vxe-input>
              <!-- v-if="modulePoitPre.includes('XTGN005')" -->
              <vxe-button  type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="handleSearch"></vxe-button>
              <!-- v-if="modulePoitPre.includes('XTGN001')" -->
              <vxe-button  type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="handleAdd(clickmoduleId, '', '')"></vxe-button>
              <!-- v-if="modulePoitPre.includes('XTGN004')" -->
              <vxe-button  type="text" icon="vxe-icon-save" content="保存" class="button-blue" :loading="saveLoading" @click="saveList"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tablebox">
            <vxe-table class="mytable-scrollbar" align="left" border="inner" ref="functionTable" height="auto" :row-config="{ isCurrent: true, isHover: true }" @current-change="menuClick" :loading="showLoading" :tree-config="{}" :column-config="{ resizable: true }" :data="menuList" :edit-config="{
                trigger: 'click',
                mode: 'cell',
                showStatus: true
              }" resizable show-overflow keep-source>
              <vxe-column field="title" width="150" title="名称" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                <template #edit="{ row }">
                  <vxe-input v-model="row.title" type="text"></vxe-input>
                </template>
              </vxe-column>
              <!-- <vxe-column
                field="code"
                width="50"
                title="编号"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
                align="center"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.code" type="text"></vxe-input>
                </template>
              </vxe-column> -->
              <vxe-column field="sn" width="60" title="顺序号" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                <template #edit="{ row }">
                  <vxe-input v-model="row.sn" type="text"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="isAssembly" width="80" title="是否组件" align="center">
                <template #default="{ row }">
                  <vxe-switch v-model="row.isAssembly" size="mini" open-label="是" close-label="否" open-value="1" close-value="0"></vxe-switch>
                  <!-- <el-switch
                    v-model="row.isAssembly"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                  /> -->
                </template>
              </vxe-column>

              <vxe-column field="isReport" width="80" title="是否报表" align="center">
                <template #default="{ row }">
                  <vxe-switch v-model="row.isReport" size="mini" open-label="是" close-label="否" open-value="1" close-value="0"></vxe-switch>
                </template>
              </vxe-column>
              <vxe-column field="isTool" width="90" title="是否工具栏显示" align="center">
                <template #default="{ row }">
                  <vxe-switch v-model="row.isTool" size="mini" open-label="是" close-label="否" open-value="1" close-value="0"></vxe-switch>
                </template>
              </vxe-column>
              <vxe-column field="isDictMenu" width="90" title="是否字典型菜单" align="center">
                <template #default="{ row }">
                  <vxe-switch v-model="row.isDictMenu" size="mini" open-label="是" close-label="否" open-value="1" close-value="0"></vxe-switch>
                </template>
              </vxe-column>

              <vxe-column field="reportName" title="模板名称" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left" width="120">
                <template #default="{ row }">
                  <span>{{ row.reportName }}</span>
                </template>

                <template #edit="{ rowIndex }">
                  <SelectDataGrid :url="'/api/pubReport/getReportByAllReq'" :column="[
                      { field: 'code', title: '编号' }, //列标题
                      { field: 'name', title: '名称' }
                    ]" :searchParam="{
                      menuId: menuIdData.menuId
                    }" :isPage="false" @SelectCellClick="
                      (e) => {
                        selectRow(e, rowIndex);
                      }
                    "></SelectDataGrid>
                </template>
              </vxe-column>

              <vxe-column width="120" field="reportUrl" title="模版路径" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                <template #edit="{ row }">
                  <vxe-input v-model="row.reportUrl" type="text"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="url" title="路径" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left" width="160px">
                <template #edit="{ row }">
                  <vxe-input v-model="row.url" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="openWith" title="组件弹框模式" :edit-render="{ autofocus: '.vxe-input--inner' }" align="center" width="120">
                <template #default="{ row }">
                  <el-select v-model="row.openWith" filterable>
                    <el-option v-for="tkms in tkmsList" :key="tkms.id" :label="tkms.name" :value="tkms.code"></el-option>
                  </el-select>
                </template>
              </vxe-column>

              <vxe-column field="parentName" width="140" title="所属上级" :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                <template #edit="{ row }">
                  <vxe-input v-model="row.parentName" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="icon" width="50" title="图标" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <el-icon size="17" class="icon">
                    <component :is="row.icon"></component>
                  </el-icon>
                </template>
                <template #edit="{ row }">
                  <vxe-input v-model="row.icon" type="text" @focus.once="showSelectIocn"></vxe-input>
                  <SelectIcon ref="refselectIcon" @SelectIcon="selectIcon1"></SelectIcon>
                </template>
              </vxe-column>

              <vxe-column title="操作" width="90" align="center" fixed="right">
                <template #default="{ row }">
                  <!-- 新建子级按钮 -->
                  <el-tooltip class="item" effect="dark" content="新建子菜单" placement="right">
                    <vxe-button type="text" status="primary" circle @click="handleAdd(clickmoduleId, row.id, row)">
                      <el-icon>
                        <CirclePlus />
                      </el-icon></vxe-button>
                  </el-tooltip>
                  <vxe-button type="text" status="danger" circle @click="deleteResGroup(row)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, watch, computed } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';

import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { AppStore } from '@/stores/store';
import SelectIcon from '@/components/SelectIcon.vue';
import SelectDataList from '@/components/SelectDataList.vue';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import { log } from 'console';

let { proxy }: any = getCurrentInstance();
//暴露属性和方法
defineExpose({
  initPage
});
let store = AppStore();

// 子组件ref名称
let refselectIcon = ref(null);

// 获取模块id
const moduleId = localStorage.getItem('moduleId');
let modulePointMap = store.userInfo.modulePointMap;
// 功能点权限
let modulePoitPre = reactive([]);
// 通过权限获取功能点
function getModulePointMap() {
  if (Object.keys(modulePointMap).includes(moduleId)) {
    modulePoitPre.push(...modulePointMap[moduleId]);
  }
}

// 模块id
let clickmoduleId = '';

// 屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);

// 用户输入关键字
let keywords = ref('');

// 树形数据
let menuList: any = reactive([]);
// 功能数据
let functionList: any = reactive([]);

//选中的路径
let selectedValue = reactive([]);
//获取当前点击的菜单Id
let menuIdData = reactive({
  menuId: ''
});

// 弹窗数据
let form = reactive({});

// 资源类型下拉数据
let typeList = reactive([
  { value: 1, label: '菜单' },
  { value: 2, label: '组件' },
  { value: 3, label: '报表' }
]);

// 加载中 loading效果状态
let showLoading = ref(false); //刷新
let saveLoading = ref(false); //保存
// 表单规则
const formRule = reactive({
  code: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到32个字符',
      trigger: 'blur'
    }
  ],
  title: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ]
});

let tkmsList: any = reactive([]); //检验组option下拉数据
// 获取检验组option下拉数据
function getDictDetailList() {
  tkmsList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'TKMS' } })
    .then((res: any) => {
      //console.log('reportTypeList---------------',reportTypeList);
      tkmsList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取弹框模式下拉数据异常', VxeNotifyType.error);
    });
}

//下拉选择之后触发保存当前
function selectchange(e: any) {
  // console.log('是否触发', e);

  //  console.log('----------e---------',e);
  //  console.log('----------row---------',row);
  //  console.log('----------rowIndex---------',rowIndex);
  //  console.log('----------column---------',column);
  e.aimKeys.forEach((item: any) => {
    if (e.isChild) {
      menuList[e.childIndex][item.targetField] = e.row[item.sourceField];
      if (item.targetField === 'report') {
        menuList[e.childIndex].reportUrl =
          '?id=' + e.row[item.sourceField].id + '&name=' + e.row[item.sourceField].name;
      }
      // console.log('menuList', menuList);
    } else {
      //表单用
    }
  });
}
onMounted(() => {
  getModulePointMap();
  getDictDetailList();
});

function initPage(moduleId: any) {
  clickmoduleId = moduleId;
  getMenuList();
}

// 获取菜单树型数据
function getMenuList() {
  showLoading.value = true;
  menuList.length = 0; //放入数据前清空数
  proxy.$http.get('/api/sys/menuList', { params: { moduleId: clickmoduleId } }).then((res: any) => {
    showLoading.value = false;
    // console.log('菜单数据', res.data.menuList);
    menuList.push(...res.data.menuList);
  });
}

// 当前点击的行
let menuClickRow = null;
// 点击行的下标
let MenuClickIndex = null;
// 获取当前行数据
let menuClick = ({ row, rowIndex }) => {
  menuClickRow = row;
  MenuClickIndex = rowIndex;
  // console.log('点击当前行的下标', menuClickRow);
  menuIdData.menuId = row.id;
};

let functionTable = ref();

// 新建父级菜单
async function handleAdd(clickmoduleId, parentId, row) {
  const $table = functionTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      id: '',
      code: '', //编号
      title: '', //名称
      icon: '', //图标地址
      moduleId: clickmoduleId, //模块id
      order: null, //顺序号
      iconSelected: '',
      parentId: parentId, //父级菜单id
      isAssembly: '0', //是否为组件
      isReport: '0', //是否为表单
      isTool: '0', //是否工具栏显示
      isDictMenu: '0' //是否字典型菜单
    };
    //departList.push(record);
    $table.loadData(menuList);
    const { row: newRow } = await $table.insertAt(record, -1);
    // 设置编辑行
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }
  }
}

// 点击修改新增保存
async function saveList() {
  saveLoading.value = true;
  // 获取表格实例
  const $Xtable = functionTable.value;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords();

    // 拿到列表中id为空的为新增
    const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e: any) => {
      let moduleAddParam = e;
      proxy.$http
        .post('/api/sys/editMenu', moduleAddParam)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('修改异常', VxeNotifyType.error);
        });
    });

    //新增一级菜单
    InsertRecords.forEach((e: any) => {
      proxy.$http
        .post('/api/sys/addMenu', e)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('创建成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('创建异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      getMenuList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}
// 点击删除
async function deleteResGroup(row: any) {
  const $atble = proxy.$refs.functionTable;

  proxy
    .$confirm('您确定要删除此条菜单数据吗？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      if (row.id) {
        proxy.$http
          .delete('/api/sys/deleteMenu/' + row.id)
          .then((res: any) => {
            if (res.status.code === 400) {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            } else {
              VxeMessage('删除成功', VxeNotifyType.success);
            }
            getMenuList();
          })
          .catch((err: any) => {
            VxeMessage('删除异常', VxeNotifyType.error);
          });
      } else {
        console.log(11111, $atble);

        $atble.remove(row);
        VxeMessage('删除成功', VxeNotifyType.success);
      }
    });
}

// 点击刷新
function handleSearch() {
  getMenuList();
}

// 关键字搜索
function search() {
  menuList.length = 0;
  proxy.$http
    .get('/api/sys/menuList', {
      params: { keywords: keywords.value, moduleId: clickmoduleId }
    })
    .then((res: any) => {
      // console.log('菜单', res.data.menuList);
      menuList.push(...res.data.menuList);
    });
}

let keyup = (e: any) => {
  if (e.$event.code == 'Enter') {
    search();
  }
};

function selectIcon1(icon: any) {
  menuClickRow.icon = icon;
}

// 点击放大镜传递组件
function showSelectIocn() {
  console.log(refselectIcon.value.initPage);

  refselectIcon.value.initPage(true);
}

// 获取组件当前行数据
function selectRow(row, index) {
  menuList[index].reportName = row.name;
  menuList[index].reportId = row.id;
  menuList[index].reportUrl = '?id=' + row.id + '&name=' + row.name;
  //console.log(menuList[index].reportName);
}
// 获取组件当前行数据
function selectRowTkms(row, index) {
  console.log(row);
  menuList[index].openWith = row.code;

}

</script>
<style lang="scss" scoped>
#MenList {
  height: 100%;
  width: 100%;

  // 附加按钮间距
  .button-blue {
    margin: 5px 0 5px 5px;
  }

  .menuTable {
    height: 100%;

    .tablebox {
      background-color: #fff;
      height: calc(100% - 39px);
    }
  }
}

:deep(.vxe-table--render-default .vxe-table--border-line) {
  border: none !important;
}

// 开关开启背景颜色
:deep(.is--on > .vxe-switch--button) {
  background-color: $vxe-switch-on;
}

// 开关关闭背景颜色
:deep(.is--off > .vxe-switch--button) {
  background-color: $vxe-switch-off;
}
</style>
